#ifdef __GNUC__
#include <bits/stdc++.h>
#else
#include <vector>
#include <queue>
#endif // __GNUC__

using namespace std;

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        if (n <= 0) return {};
        vector<vector<int>> res(n, vector<int>(n));
        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;

        int k = 1;
        while (true) {
            for (int i = top, j = left; j <= right; ++j) {
                res[i][j] = k++;
            }
            if (++top > bottom) break;

            for (int i = top, j = right; i <= bottom; ++i) {
                res[i][j] = k++;
            }
            if (left > --right) break;

            for (int i = bottom, j = right; j >= left; --j) {
                res[i][j] = k++;
            }
            if (top > --bottom) break;

            for (int i = bottom, j = left; i >= top; --i) {
                res[i][j] = k++;
            }
            if (++left > right) break;
        }
        return res;
    }
};
